package org.example.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.example.dao.RouterparametersDao;
import org.example.entity.A0651C073InVo;
import org.example.entity.A999999999InVo;
import org.example.po.Routerparameters;
import org.example.po.Routerrule;
import org.example.utils.CodeCache;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * @version 1.0
 * @description TODO
 * @date 2024/10/15 21:57
 */
@RestController
public class CacheController {
    private static Logger LOGGER = LoggerFactory.getLogger(CacheController.class);

    @Resource
    private RouterparametersDao routerparametersDao;

    /***
     * 更新数据库后操作
     * @return void
     * @date 2024/10/15 21:54
     */
    @PostMapping("/A999999999")
    public void doA999999999(@RequestBody A999999999InVo inVo){
        // 更新数据库后，修改缓存的接口
        CodeCache.isUsing = false;
        Routerparameters routerparameters = inVo.getRouterparameters();
        QueryWrapper<Routerparameters> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("rulename",routerparameters.getRulename());
        queryWrapper.eq("projectName",routerparameters.getProjectname());
        queryWrapper.eq("ruleid",routerparameters.getRuleid());
        Routerparameters obj = routerparametersDao.selectOne(queryWrapper);
        try {
            if(obj == null){
                routerparametersDao.insert(routerparameters);
            }else{
                routerparametersDao.update(routerparameters,queryWrapper);
            }
            LOGGER.info("策略更新成功");
        }catch(Exception e){
            LOGGER.info("策略更新失败" + e);
            CodeCache.isUsing = true;
        }
        int size = CodeCache.routerparametersMap.size();
        CodeCache.routerparametersMap = new HashMap<>(size);
        List<Routerparameters> list= routerparametersDao.selectList(null);
        for (Routerparameters routerparameter: list) {
            String rulename = routerparameter.getRulename();
            String projectname = routerparameter.getProjectname();
            String key = rulename + "_" + projectname;
            List<Routerparameters> list1 = CodeCache.routerparametersMap.getOrDefault(key, new ArrayList<>());
            list1.add(routerparameter);
            CodeCache.routerparametersMap.put(key, list1);
        }
        CodeCache.isUsing = true;
        LOGGER.info("缓存更新完成");
    }
}
